//
//  fmdbTool.m
//  ChatDemo-UI2.0
//
//  Created by zz on 16/5/19.
//  Copyright © 2016年 zz. All rights reserved.
//

#import "fmdbTool.h"
#import "StudentsModel.h"
@implementation fmdbTool

static FMDatabase *_db;
+(void)initialize{ 
    
    //1.获取文件路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *dbpath = [path stringByAppendingPathComponent:@"syfrienddb.db"];
    _db = [FMDatabase databaseWithPath:dbpath];
    
    if (![_db open]) {
        
        NSLog(@"数据库打开失败");
    }
   
    
    //存放班级里所有学生信息的表
    [_db executeUpdate:@"create table if not exists t_studentsInfo (id integer primary key autoincrement,name text,studentid text,dict bolb);"];

    
    return;
    
}


#pragma mark -存放班级里面的学生信息数组
+(BOOL)saveStudentsInfoWithArray:(NSArray *)array{
    
    //先清空数据库数据
    [_db executeUpdate:@"delete from t_studentsInfo"];
    [_db executeUpdate:@"update sqlite_sequence set seq = 0 where name = 't_studentsInfo'"];
    
    for (StudentsModel *model in array) {

        NSString *name = model.studentname;
        NSString *studentid = [NSString stringWithFormat:@"%ld",(long)model.studentid];

        NSDictionary *dic = model.mj_keyValues;

        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
        [_db executeUpdate:@"insert into t_studentsInfo (name,studentid,dict) values(?,?,?)",name,studentid,data];
    }
   
    return YES;
}

+(BOOL)removeAllStudentsData{
    
    [_db executeUpdate:@"delete from t_studentsInfo"];
    [_db executeUpdate:@"update sqlite_sequence set seq = 0 where name = 't_studentsInfo'"];
    return YES;
}

+(NSArray *)searchStudentsWithNameStr:(NSString *)str{
    
    NSString *sql = [NSString stringWithFormat:@"select * from t_studentsInfo where name like '%%%@%%'",str];
    
    FMResultSet *set = [_db executeQuery:sql];
    
    NSMutableArray *arr = [NSMutableArray array];
    
    while ([set next]) {
        
        NSData *data = [set dataForColumn:@"dict"];
        
        NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        
        StudentsModel *model = [StudentsModel mj_objectWithKeyValues:dic];
        [arr addObject:model];
    }
    
    return arr;
}

@end
